package org.arain.baseii.login;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.arain.baseii.aspect.annotation.SystemLoginLog;
import org.arain.baseii.exception.UseException;
import org.arain.baseii.pojo.SysUser;
import org.arain.baseii.system.resources.SysResourcesService;
import org.arain.baseii.system.user.SysUserService;
import org.arain.baseii.utils.AppUtils;
import org.arain.baseii.utils.ArainResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
	@Autowired
	private SysResourcesService sysResourcesService;
	@Autowired
	private SysUserService sysUserService;
	
	@RequestMapping("system/login")
	public String login_page() {
		return "login/login_01";
	}
	
	@SystemLoginLog
	@RequestMapping("system/login.do")
	@ResponseBody
	public ArainResult login_do(HttpServletRequest request,LoginDto loginDto) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getUsername(), DigestUtils.md5DigestAsHex((loginDto.getPassword().getBytes())));
		try {
			subject.login(token);
			SysUser user = (SysUser) subject.getPrincipal();
			user.setPassword("");
			HttpSession session = request.getSession();
			session.setAttribute("userInfo", user);
			session.setMaxInactiveInterval(30*60);
			return ArainResult.ok();
		} catch(Exception e) { 
			throw new UseException("账号或密码错误");
		}
	}
	
	@SuppressWarnings("rawtypes")
	@RequestMapping("container")
	public String container(Model model,HttpServletRequest request) {
		List list = sysResourcesService.load_user_resources(request);
		String image = sysUserService.load_head_image(AppUtils.getUserId());
		if(StringUtils.isBlank(image)) {
			image = "/base/images/head.jpg";
		}
		String rank = sysUserService.load_rank();
		model.addAttribute("user_head", image);
		model.addAttribute("container", list);
		model.addAttribute("user_rank", rank);
        return "login/container";
	}
	
	@RequestMapping("system/main")
	public String main(Model model) {
        return "login/main";
	}
	
	@RequestMapping(value = "ajaxLoadUserChildrenResource.do", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String loadUserChildrenResource(HttpServletRequest request, Long pid) {
		return sysResourcesService.load_user_children_resources(request, pid);
	}
	
	@RequestMapping("system/load_heart")
	@ResponseBody
	public ArainResult load_heart(HttpServletRequest request) {
		return ArainResult.ok();
	}
}
